﻿using System.Web.Mvc;
using Blog.Infrastructure.DataAcces.Services.Abstractisations;
using Blog.Presentation.Models.Input;

namespace Blog.Presentation.Controllers
{
    public class AccountController : Controller
    {
        protected IMembershipService membershipService;
        protected IAuthenticationService authenticationService;
        //
        // GET: /Account/
        public AccountController(IMembershipService membershipService, IAuthenticationService authenticationService)
        {
            this.membershipService = membershipService;
            this.authenticationService = authenticationService;
        }

        public ViewResult Logon()
        {
            return View(new LoginInput());
        }

        [HttpPost]
        public ActionResult Logon(LoginInput loginInput, string returnUrl="")
        {
            if(membershipService.ValidateUser(loginInput.UserName, loginInput.Password))
            {
                authenticationService.SignIn(loginInput.UserName, loginInput.RememberMe);
                if (Url.IsLocalUrl(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                return RedirectToAction("Index", "Home");
             }

            return View(loginInput);
        }

        public ActionResult New()
        {
           return View(new NewUserInput());
        }

        [HttpPost]
        public RedirectToRouteResult New(NewUserInput userinput)
        {
            if (ModelState.IsValid)
            {
                membershipService.CreateUser(userinput.UserName, userinput.Password, userinput.Email);
            }

            return RedirectToAction("Logon");
        }

        public RedirectToRouteResult Signout()
        {
            authenticationService.SignOut();
            return RedirectToAction("Index","Home");
        }
    }
}
